package com.emm.yixun.website.controller.marketing;
//框架包
import java.util.ArrayList;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.emm.yixun.common.model.Project;
//变化的引用
import com.emm.yixun.common.model.SalesGroup;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.dto.SalesGroupDto;
import com.emm.yixun.common.model.dto.SalesGroupViewDto;
import com.emm.yixun.common.page.Page;
//common
import com.emm.yixun.common.page.PageUtil;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.estate.service.ProjectServiceFacade;
import com.emm.yixun.marketing.service.SalesGroupServiceFacade;
//website
import com.emm.yixun.website.common.ajax.AjaxRes;
import com.emm.yixun.website.common.utils.base.Const;
import com.emm.yixun.website.common.utils.security.ShiroUtil;
import com.emm.yixun.website.controller.base.BaseController;
import com.emm.yixun.website.vo.common.ExtResultVo;


@Controller
@RequestMapping("/marketing/salesGroup/")
public class SalesGroupController extends BaseController<SalesGroup>{
	
	@Autowired
	private SalesGroupServiceFacade salesGroupServiceFacade;
	
	@Autowired
	private ProjectServiceFacade projectServiceFacade;
	
	@RequestMapping(value="index")
	public String index(ModelMap map,HttpServletRequest request){
		if(doSecurityIntercept(Const.RESOURCES_TYPE_MENU)){
			//查询菜单按钮权限
			map.put("permitBtn", getPermissionBtnArray());
			map.put("menu", request.getParameter("menu"));
			return "/marketing/salesGroup/list";
		}
		return Const.NO_AUTHORIZED_URL;
	}
	
	@RequestMapping(value = "addFrom")
	public ModelAndView addForm(Long salesGroupId){
		ModelAndView mv = new ModelAndView("/marketing/salesGroup/addFrom").addObject("salesGroupId", salesGroupId);
		if(salesGroupId!=null){
			Response<SalesGroup> sales = salesGroupServiceFacade.findById(salesGroupId);
			if(sales.isSuccess()){
				mv.addObject("salesGroup", JSONObject.fromObject(sales.getEntity()));
			}
		}
		
		return mv;
	}
	
	//新增返回实体对象
	@RequestMapping(value="add", method=RequestMethod.POST)
	@ResponseBody
    public AjaxRes  add(SalesGroupDto dto){
    	AjaxRes ar=getAjaxRes();
    	
    	/*
    	 *1.判断权限 
    	 *2.调用新增接口
    	 *3.返回信息
    	*/
        if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"marketing:salesGroup:add"))){
        	try {
        		User user=ShiroUtil.getCurrentUser();
        		dto.setMerchantId(user.getMerchantId());
        		dto.setCreateUserId(user.getId());
        		dto.setDelFlag("0");
        		dto.setUpdateUserId(user.getId());
        		dto.setUpdateTime(new Date());
				Response<SalesGroupDto> response=salesGroupServiceFacade.save(dto);
				if(response.isSuccess()){
					ar.setSucceedMsg(Const.SAVE_SUCCEED);
				}else{
					ar.setFailMsg(Const.SAVE_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.SAVE_FAIL);
			}
    	}
    	return ar;
    }
	//查看
	@RequestMapping(value="view", method=RequestMethod.POST)
	@ResponseBody
    public AjaxRes  view(Long id){
    	AjaxRes ar=getAjaxRes();
    	/*
    	 *1.判断权限 
    	 *2.调用查看接口
    	 *3.返回信息
    	*/
        if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"marketing:salesGroup:view"))){
        	try {
				Response<SalesGroup> response=salesGroupServiceFacade.findById(id);
				if(response.isSuccess()){
					ar.setSucceed(response.getEntity());
				}else {
					ar.setFailMsg(Const.DATA_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.DATA_FAIL);
			}
    	}
    	return ar;
    }
	
	//修改
	@RequestMapping(value="edit", method=RequestMethod.POST)
	@ResponseBody
    public AjaxRes  edit(SalesGroupDto dto){
    	AjaxRes ar=getAjaxRes();
    	/*
    	 *1.判断权限 
    	 *2.调用修改接口
    	 *3.返回信息
    	*/
        if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"marketing:salesGroup:edit"))){
        	try {
        		Response<Integer> response=salesGroupServiceFacade.updateByPrimaryKey(dto, true);
				if(response.isSuccess()){
					ar.setSucceedMsg(Const.UPDATE_SUCCEED);
				}else{
					ar.setFailMsg(Const.UPDATE_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.UPDATE_FAIL);
			}
    	}
    	return ar;
    }
	
	//关闭分组
	@RequestMapping(value="closeGroup", method=RequestMethod.POST)
	@ResponseBody
    public AjaxRes  closeGroup(Long id){
    	AjaxRes ar=getAjaxRes();
    	/*
    	 *1.判断权限 
    	 *2.调用查看接口
    	 *3.返回信息
    	*/
        if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"marketing:salesGroup:closeGroup"))){
        	try {
        		Response<Boolean> response=salesGroupServiceFacade.closeGroup(id);
				if(response.isSuccess()){
					ar.setSucceedMsg(Const.DEL_SUCCEED);
				}else {
					ar.setFailMsg(Const.DEL_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.DEL_FAIL);
			}
    	}
    	return ar;
    }
	
	
	/**
	* 方法描述 : 删除项目组
	* 创建者：ThinkPad 
	* 项目名称： emm-website
	* 类名： SalesGroupController.java
	* 版本： v1.0
	* 创建时间： 2016年6月21日 上午11:03:03
	* @param id
	* @return AjaxRes
	 */
	@RequestMapping(value = "delete")
	public @ResponseBody AjaxRes delete(Long id){
		AjaxRes ar=getAjaxRes();
		 if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"marketing:salesGroup:delete"))){
			 try {
	        		Response<Integer> response=salesGroupServiceFacade.deleteByPrimaryKey(id);
					if(response.isSuccess()){
						ar.setSucceedMsg(Const.DEL_SUCCEED);
					}else {
						ar.setFailMsg(Const.DEL_FAIL);
					}
				} catch (Exception e) {
					logger.error(e.toString(),e);
					ar.setFailMsg(Const.DEL_FAIL);
				}
		 }
		 return ar;
	}
	
	
	
	//分页查询
	@RequestMapping(value="list")
	@ResponseBody
    public Page<SalesGroupViewDto>  list(SalesGroupDto dto,Integer page,Integer limit){
    	/*
    	 *1.判断权限 
    	 *2.调用分页查询接口
    	 *3.返回信息
    	*/
        if(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"marketing:salesGroup:list")){
        	try {
        		User user = ShiroUtil.getCurrentUser();
        		dto.setPermissionUserId(user.getId());
			    dto.setMerchantId(user.getMerchantId());
        		//权限组数据权限资源缓存
			    String resourcesCode = dto.getResourcesCode();
        		if(StringUtils.isBlank(resourcesCode)){
        			resourcesCode = ShiroUtil.getDataPermissionResources(dto.getResourcesName());
            			dto.setResourcesCode(resourcesCode);
        		}
        		ShiroUtil.setDataPermissionResources(dto.getResourcesName(), resourcesCode);
        		dto.setOrders("t.sort asc, t.project_code, t.status");
        		Page<SalesGroupViewDto> response=salesGroupServiceFacade.groupListPage(dto, PageUtil.begin(page, limit),limit);
                if(response.getSuccess()){
                    if(null==response.getRows())response.setRows(new ArrayList<SalesGroupViewDto>());
                	response.setPageNumber(limit);
                	return response;
                }
			} catch (Exception e) {
				logger.error(e.toString(),e);
			
			}
    	}
    	return new Page<SalesGroupViewDto>();
    }
	
	@RequestMapping(value="responseSalesGroup")
	 public @ResponseBody ExtResultVo responseSalesGroup(Long id){
		ExtResultVo vo= new ExtResultVo();
		 try {
			 Response<SalesGroup> salesGroup = salesGroupServiceFacade.findById(id);
			 if(salesGroup.isSuccess()){
				 SalesGroupDto groupDto = new SalesGroupDto();
				 SalesGroup obj = salesGroup.getEntity();
				 Project project = projectServiceFacade.findById(obj.getProjectId()).getEntity();
				 groupDto.setProjectCN(project.getProjectName());
				 groupDto.setName(obj.getName());
				 if(obj.getStatus().equals("0")){
					 groupDto.setStatusCN("正常");
				 }else if(obj.getStatus().equals("1")){
					 groupDto.setStatusCN("已关闭");
				 }
				 groupDto.setSort(obj.getSort());
				 vo.setData(groupDto);
				 vo.setSuccess(true);
			 }
			 
		} catch (Exception e) {
			vo.setErrorMessage(e.getMessage());
			logger.error("responseSalesGroup error: ", e);
		}
		 return vo;
	 }
}
